package com.lm.rdf4j.example;

import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.impl.LinkedHashModel;
import org.eclipse.rdf4j.model.util.Values;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.query.QueryLanguage;
import org.eclipse.rdf4j.query.TupleQuery;
import org.eclipse.rdf4j.query.TupleQueryResult;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.eclipse.rdf4j.sail.memory.MemoryStore;

public class BasicRDF4JExample {
    public static void main(String[] args) {
        // 创建一个内存中的 RDF 存储库
        Repository repo = new SailRepository(new MemoryStore());
        repo.init();

        try (RepositoryConnection conn = repo.getConnection()) {
            // 定义命名空间和 IRI
            String ex = "http://example.org/";
            IRI picasso = Values.iri(ex, "Picasso");
            IRI artist = Values.iri(ex, "Artist");

            // 创建模型并添加三元组：Picasso 是一个 Artist
            Model model = new LinkedHashModel();
            model.add(picasso, RDF.TYPE, artist);
            conn.add(model);

            // 使用 SPARQL 查询模型中所有类型为 Artist 的资源
            String queryString = "PREFIX ex: <http://example.org/> " +
                    "SELECT ?s WHERE { ?s a ex:Artist . }";
            TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
            try (TupleQueryResult result = query.evaluate()) {
                while (result.hasNext()) {
                    System.out.println("查询结果：" + result.next().getValue("s"));
                }
            }
        }
        repo.shutDown();
    }
}
